<template>
    <a-card :bordered="false">


        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <!-- <a-row style="display: flex;position: absolute;right: 20px;">
                    <a-col :md="24" :sm="24">
                        日期区间:{{ startRange }}{{ endRange ? '~' : '' }}{{ endRange }}
                    </a-col>
                </a-row> -->
                <a-row :gutter="10">
                    <!-- <a-col :md="4" :sm="24">
                        <a-form-item label="查询类别">
                            <a-select v-model="queryParam.condition" allowClear>
                                <a-select-option key="code">编码</a-select-option>
                                <a-select-option key="name">名称</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="3" :sm="24">
                        <a-form-item label="业务员">
                            <a-input v-model="queryParam.Saler" placeholder="请输入业务员" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <div style="display: flex;">
                            <a-form-item label="产品名称">
                                <a-input style="width: 150px;" v-model="queryParam.InventoryName" placeholder="请输入产品名称"
                                    @keydown.enter="getDataList" />
                            </a-form-item>
                            <a-form-item style="margin-left: 8px;" label="类型">
                                <a-select style="width: 100px;margin-left: 8px;" @change="changeTime" name="Status"
                                    :default-value="'全部'">
                                    <a-select-option :value="i" v-for="(i, index) in ['全部', '开票收入', '暂估收入', '退货']"
                                        :key="i">
                                        {{ i }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </div>
                    </a-col>
                    <!-- <a-col :md="4" :sm="24">
                        <a-form-item label="选择仓库">
                            <a-select ref="select" placeholder="请选择仓库" v-model:value="queryParam.Warehouse">
                                <a-select-option v-for="item in selectOption" :key="item.code" :value="item.code">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="15" :sm="24">
                        <!-- <a-select style="width: 100px;margin-left: 8px;" v-model="selectTime" @change="changeTime"
                            name="radioGroup" :default-value="0">
                            <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                                {{ i }}
                            </a-select-option>
                        </a-select>
                        <a-range-picker style="width: 220px;margin:0 8px;" :placeholder="['开始月份', '结束月份']"
                            format="YYYY-MM" :value="time" :mode="['month', 'month']" :open="monthPickShow"
                            @panelChange="handlePanelChange2" :disabled="timeDisabled" @openChange="handleOpenChange" /> -->
                        <a-month-picker placeholder="选择月份" :defaultValue="moment(new Date,'YYYY-MM')"
                            @change="onChangeMonth" style="margin-right: 8px;" />
                        <!-- <a-range-picker style="margin-left: 8px;width: 220px;" :disabled="timeDisabled" v-model="time" /> -->
                        <!-- <a-switch class="my-switch" v-model:checked="tableType" checked-children=""
                            @change="() => { getDataList() }" un-checked-children="列表" /> -->
                        <a-radio-group v-model:value="tableType" @change="getDataList" name="radioGroup">
                            <a-radio :value="0">列表</a-radio>
                            <a-radio :value="1">透视表</a-radio>
                        </a-radio-group>
                        <!-- <a-button style="margin-left: 10px;" type="primary"
                            @click="() => { showSpecial = true }">特殊单据<span
                                style="padding:0 5px;background: red;margin-left: 3px;font-size: 10px; border-radius: 20px;"
                                v-show="selectRowsData.length > 0">{{
                                selectRowsData.length }}</span>
                        </a-button> -->
                        <a-button style="margin-left: 10px;" type="primary" @click="() => {
        this.pagination.current = 1
        this.getDataList()
    }
        ">查询
                        </a-button>
                        <a-button style="margin-left: 10px;" type="primary" @click="() => {
        showCalcModal = true;
    }
        ">计算
                        </a-button>
                        <a-button style="margin-left: 8px;margin-right: 8px;" @click="repossess">重置</a-button>
                        <a-button type="primary" icon="download" :disabled="!id" @click="downloadTemplate">导出</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <div v-if="tableType">
            <iframe style="border:none; width:85vw;min-height:70vh" :src="href"></iframe>
        </div>

        <div v-else style="position:relative;">
            <a-table :rowClassName="(record) => record.Status == '暂估收入(退货)' ? 'TableActive' : ''" ref="table"
                :bordered="true" :columns="columns" :dataSource="data" :loading="loading" :pagination="pagination"
                :scroll="{ y: 'calc(100vh - 330px)' }" size="small" @change="handleTableChange">
                <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
                <span slot="Status" slot-scope="text, record">
                    <template>
                        <a-tag :color="text == '开票收入' ? '#87d068' : text == '暂估收入' ? '#108ee9' : '#f50'">{{ text
                            }}</a-tag>
                    </template>
                </span>
            </a-table>
            <div style="display: flex;position: absolute;bottom: 0px;">
                <p>售价总计:{{ (filterObj.SaleTotal || 0) | NumberFormats }}</p>
                <p style="margin: 0 20px;">成本总计:{{ (filterObj.CostTotal || 0) | NumberFormats }}</p>
                <p>毛利总计:{{ (filterObj.GrossProfitTotal || 0) | NumberFormats }}</p>
                <p style="margin: 0 20px 0 50px;">开票收入总计:{{ (filterObj.InvoiceTotal || 0) | NumberFormats }}</p>
                <p>暂估收入总计:{{ (filterObj.EstimatedTotal || 0) | NumberFormats }}</p>
                <p style="margin: 0 20px;">退货总计:{{ (filterObj.ReturnTotal || 0) | NumberFormats }}</p>
            </div>
        </div>
        <a-modal :visible="showSpecial" width="80%" @cancel="() => { showSpecial = false }" @ok="selectSpecial">
            <Special ref="special"></Special>
        </a-modal>
        <a-drawer :visible="showCalcModal" width="580px" @close="() => { showCalcModal = false }">
            <Calc ref="calc"></Calc>
        </a-drawer>
    </a-card>
</template>

<script>
import Token from '@/utils/cache/TokenCache'
import moment from 'moment'
import { download } from '@/components/download'
import Special from "./special.vue"
import Calc from "../Calc/List.vue"
const columns = [
    // { title: '', dataIndex: 'SalesOrderNo', },
    // {
    //     title: '日期',
    //     dataIndex: 'time',
    //     align: 'center',
    //     customRender: (value, row) => {
    //         return row.time.substring(0, 10)
    //     },

    // },
    { title: '业务员', dataIndex: 'Saler', },
    { title: '产品名称', dataIndex: 'InventoryName', },
    { title: '规格', dataIndex: 'Inventoryspec', },
    { title: '仓库', dataIndex: 'FinStoreName', width: '120px' },
    { title: '计量单位', dataIndex: 'UnitByFin', width: '80px' },
    { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right', width: '100px' },
    { title: '金额', dataIndex: 'InvoicingAmount', align: 'right', width: '100px' },
    { title: '成本单价', dataIndex: 'CostPrice', align: 'right', width: '100px' },
    { title: '成本', dataIndex: 'CostAmount', align: 'right', width: '100px' },
    { title: '毛利', dataIndex: 'GrossProfit', align: 'right', width: '100px' },
    { title: '类型', dataIndex: 'Status', align: 'center', width: '100px', scopedSlots: { customRender: 'Status' } },
    // { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, }
]

export default {
    components: {
        Token,
        Calc,
        Special
    },
    mounted() {

        // this.href = location.href.split('/')[0] + '//' + location.host + '/GrossProfit';
        this.$nextTick(async () => {
            await this.$http.post('/BillCode/billcodes_main/GetDataListBySingleCondition', {
            }).then(res => {
                this.selectData = res.Data;
                this.month = new Date()
                this.getDataList()
            })
            // 页面渲染完成后的回调
            // this.tableHeight = this.getTableHeight(true) + 24
            // this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
            
            // this.getSelectOptions();
        })
    },
    data() {
        return {
            headers: {
                authorization: 'Bearer ' + Token.getToken()
            },
            data: [],
            visible: false,
            tableType: 0,
            monthPickShow: false,
            pagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            filters: {},
            filterObj: {},
            sorter: { field: 'dDate', order: 'desc' },
            loading: false,
            columns,
            queryParam: {},
            visibleUpload: false,
            selectedRowKeys: [],
            time: [],
            timeDisabled: true,
            selectTime: 0,
            selectData: [],
            selectOption: [],
            month: '',
            selectRowsData: [],
            showSpecial: false,
            href: '',
            showView: true,
            showCalcModal: false,
            id:'',
        }
    },
    computed: {
        startRange() {
            if (!this.time[0]) {
                return ''
            }
            const currentDate = new Date(this.time[0]); // 获取当前日期
            const previousMonth = (currentDate.getMonth() === 0) ? 12 : currentDate.getMonth(); // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${currentDate.getMonth() === 0 ? new Date().getFullYear(this.time[0]) - 1 : new Date().getFullYear(this.time[0])}-${previousMonth}-26`
        },
        endRange() {
            if (!this.time[1]) {
                return ''
            }
            const currentDate = new Date(this.time[1]); // 获取当前日期
            const previousMonth = currentDate.getMonth() + 1; // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${new Date().getFullYear(this.time[1])}-${previousMonth}-25`
        }
    },
    methods: {
        selectSpecial() {
            this.selectRowsData = this.$refs.special.selectRows;
            this.showSpecial = false;
        },
        openhtml() {
            this.$http.post('/OrderManagement/SO_SOMain/ExportSO_SOMainAndRuleToExcel', {}).then(resJson => {
                if (resJson.Success) {
                    download(resJson.Data.fileUrl, resJson.Data.fileName)
                    this.visible = false
                } else {
                    this.$message.error(resJson.Msg)
                }
            })
        },
        repossess() {
            this.queryParam = {}
            this.changeTime('全部');
            this.getDataList();
        },
        handleTableChange(pagination, filters, sorter) {
            this.pagination = { ...pagination }
            this.filters = { ...filters }

            this.getDataList();
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        getSelectOptions() {
            this.$http.post('InvoiceManagement/Inv_InvoiceApplyMain/GetWarehouseList').then(res => {
                this.selectOption = res.Data;
            }).catch(err => {
                this.$message.error(err);
            })
        },
        handlePanelChange2(value) {
            if (this.time[1] && this.time._d != value[1]._d) {
                this.monthPickShow = false;
            }
            this.time = value;
        },
        handleOpenChange(status) {
            if (status) {
                this.monthPickShow = true;
            } else {
                this.monthPickShow = false
            }
        },
        async getDataList() {
            console.log(this.month)
            if (!this.month || this.month == 'Invalid date') {
                this.$message.error('请先选择日期区间')
                return;
            }


            this.selectedRowKeys = []
            // this.queryParam.condition='name'


            let id = this.selectData.filter(item => item.DateRange == this.timeFormat(this.month))[0].Id
            this.id = id;
            await this.$http.post('/BillCode/billcodes_main/GetTheData', {
                id: id
            }).then(res => {
                this.filterObj = res.Data
            })
            this.loading = true
            // this.showView = false;
            // await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep1', { Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "", Ids: this.selectRowsData} })
            // await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep2?StartTime=' + (this.time[0] ? this.timeFormat(this.time[0]) : "") + '&EndTime=' + (this.time[1] ? this.timeFormat(this.time[1]) : ""))
            // await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GrossProfitStep3?StartTime=' + (this.time[0] ? this.timeFormat(this.time[0]) : "") + '&EndTime=' + (this.time[1] ? this.timeFormat(this.time[1]) : ""))
            // this.showView = true;
            // await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetCostPrice', { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" })
            if (this.tableType == 1) {
                let obj = {
                    Search: { Ids: this.selectRowsData, ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
                }
                this.href = location.href.split('/')[0] + '//' + location.host + '/GrossProfit?data=' + id;
                console.log(this.href)
                return;
            }

            this.$http
                .post('/BillCode/billcodes_statistics/GetDataListByMoreCondition', {
                    PageIndex: this.pagination.current,
                    PageRows: this.pagination.pageSize,
                    SortField: 'Saler',
                    GrossProfitType: 2,
                    Search: [
                        {
                            "Condition": "Saler",
                            "Keyword": this.queryParam.Saler
                        },
                        {
                            "Condition": "InventoryName",
                            "Keyword": this.queryParam.InventoryName
                        },
                        {
                            "Condition": "ParentId",
                            "Keyword": id
                        },
                        {
                            "Condition": "Status",
                            "Keyword": this.queryParam.Status
                        }
                    ],
                })
                .then(resJson => {
                    this.loading = false
                    this.data = resJson.Data
                    this.data.forEach(item => {
                        item.InvoicingAmount = item.Status == '红冲' ? this.$options.filters.NumberFormats(item.RedAmount) : this.$options.filters.NumberFormats(item.InvoicingAmount)
                        item.CostPrice = this.$options.filters.NumberFormats(item.CostPrice)
                        item.CostAmount = this.$options.filters.NumberFormats(item.CostAmount)
                        item.GrossProfit = this.$options.filters.NumberFormats(item.GrossProfit)
                        item.InvoicingQuantity = item.InvoicingQuantity && item.InvoicingQuantity.toFixed('4')
                    })
                    if (this.data) {
                        const pagination = { ...this.pagination }
                        pagination.total = resJson.Total
                        this.pagination = pagination
                    }
                }).catch(err => {
                    this.$message.error(err);
                })
        },
        onChangeMonth(e) {
            console.log(e)
            this.month = this.timeFormat(arguments[0]);
        },
        // 导入文件类型
        handleChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.Success === false) {
                    this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
                } else {
                    this.$message.success(`${info.file.name}  文件上传成功！`)
                    this.getDataList()
                }
                this.visible = false
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 文件上传失败！`)
            }
        },
        hasSelected() {
            return this.selectedRowKeys.length > 0
        },
        handleAdd() {
            this.$refs.editForm.openForm(null, '新建销售订单主表信息')
        },
        handleEdit(id) {
            this.$refs.editForm.openForm(id, '订单详情')
        },
        //导入
        handleImport() {
            this.visibleUpload = true;
        },
        //导出
        downloadTemplate() {
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/Export', {
                SortField: 'Saler',
                GrossProfitType: 2,
                Search: [
                    {
                        "Condition": "Customer",
                        "Keyword": this.queryParam.Customer
                    },
                    {
                        "Condition": "InventoryName",
                        "Keyword": this.queryParam.InventoryName
                    },
                    {
                        "Condition": "ParentId",
                        "Keyword": this.id
                    },
                    {
                        "Condition": "Status",
                        "Keyword": this.queryParam.Status
                    }
                ],
            }, { responseType: 'blob' }).then(res => {
                const url = URL.createObjectURL(res)
                // console.log(url)
                const fileName = '业务员毛利分析表'
                const aTag = document.createElement('a')
                aTag.download = fileName
                aTag.href = url
                aTag.click()
                URL.revokeObjectURL(aTag.href)
            }).catch(err => {
                this.$message.error(err);
            })
        },
        handleDelete(ids) {
            var thisObj = this
            // this.$confirm({
            //   title: '确认删除吗?',
            //   onOk() {
            //     return new Promise((resolve, reject) => {
            //       thisObj.$http.post('/OrderManagement/SO_SOMain/DeleteData', ids).then(resJson => {
            //         resolve()

            //         if (resJson.Success) {
            //           thisObj.$message.success('操作成功!')

            //           thisObj.getDataList()
            //         } else {
            //           thisObj.$message.error(resJson.Msg)
            //         }
            //       })
            //     })
            //   }
            // })

            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                thisObj.$http
                    .post('/OrderManagement/SO_SOMain/DeleteData', ids)
                    .then(resJson => {
                        // resolve()

                        if (resJson.Success) {
                            thisObj.$message.success('操作成功!')

                            thisObj.getDataList()
                        } else {
                            thisObj.$message.error(resJson.Msg)
                        }
                    })
            })
        },
        changeTime(e) {
            this.queryParam.Status = e == '全部' ? '' : e;
        },
        timeFormat(val) {
            // 时间格式化函数
            return moment(val).format('YYYY-MM')
        },
        moment,
    }
}
</script>

<style lange="less" scoped>
.flax {
    display: flex;
    justify-content: space-between;
}

/* .download {
  float: right;
  display: flex;
  align-items: center;
} */
.my-switch.ant-switch {
    min-width: 60px;
    height: 35px;

    .ant-switch-inner {
        font-size: 25px;
    }

    &.ant-switch::after {
        width: 20px;
        height: 20px;
        top: 7px;
    }
}
/deep/ .TableActive {
    background: pink;
}
/deep/ .ant-card-body {
    padding-bottom: 0px;
  }
</style>